<template>
    <div class="content-wrapper">
        <el-row class="content-row">
            <el-col class="height-init" :span="24">
                <div class="container">
                    <el-row class="handle-box">
                        <el-input v-model="query.title" placeholder="标题" class="handle-input mr10"></el-input>
                        <el-date-picker
                                v-model="query.time"
                                type="daterange"
                                range-separator="至"
                                @change="dateChange"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch" class="ml10">搜索</el-button>
                        <el-button type="primary" icon="el-icon-plus" class="handle-del" @click="addUser" v-if="checkAuth(auths.add)">新增</el-button>
                    </el-row>
                    <el-row class="list-table-row">
                        <el-table
                                :data="tableData"
                                border
                                class="table"
                                ref="multipleTable"
                                height="100%"
                                header-cell-class-name="table-header"
                                @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" width="55" align="center"></el-table-column>
                            <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
                            <el-table-column prop="title" label="标题" show-overflow-tooltip />
                            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip>
                                <template slot-scope="scope" >
                                    {{renderTime(scope.row.createTime)}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="url" label="文章连接" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="isTop" label="是否置顶">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.isTop == 0">否</span>
                                    <span v-if="scope.row.isTop == 1">是</span>

                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="140" align="center">
                                <template slot-scope="scope">
                                    <el-button
                                            type="text"
                                            icon="el-icon-edit"
                                            @click="handleEdit(scope.$index, scope.row)"
                                            v-if="checkAuth(auths.update)"
                                    >编辑</el-button>
                                    <el-button
                                            type="text"
                                            icon="el-icon-delete"
                                            @click="handleDelete(scope.$index, scope.row)"
                                            v-if="checkAuth(auths.delete)"
                                    >删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                    <el-row class="pagination-self">
                        <el-pagination
                                background
                                layout="total, sizes, prev, pager, next"
                                :current-page="query.pageNo"
                                :page-size="query.pageSize"
                                :total="pageTotal"
                                @size-change="handleSizeChange"
                                @current-change="handlePageChange"
                        ></el-pagination>
                    </el-row>
                </div>
            </el-col>
        </el-row>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="35%" >
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="100px">
                <el-row style="height: 350px">
                    <el-form-item label="文章标题" prop="title">
                        <el-input v-model="addForm.title" placeholder="文章标题"></el-input>
                    </el-form-item>
                    <el-form-item label="文章链接" placeholder="文章链接"  prop="url">
                        <el-input v-model="addForm.url"></el-input>
                    </el-form-item>
                    <el-form-item label="是否置顶" prop="isTop">
                        <el-radio-group v-model="addForm.isTop">
                            <el-radio label="0">否</el-radio>
                            <el-radio label="1">是</el-radio>
                        </el-radio-group>
                        默认不置顶，不置顶按创建时间倒序显示
                    </el-form-item>
                    <el-form-item label="上传缩列图" prop="img">
                        <el-upload
                                :action="uploadUrl"
                                list-type="picture-card"
                                :class="{disabled:uploadNum==1}"
                                :limit="limit"
                                :file-list="picList"
                                :on-preview="handlePictureCardPreviewImg"
                                :on-success="successUploadImg"
                                :before-upload="beforeUpload"
                                :on-remove="handleRemoveImg">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisibleImg" size="tiny">
                            <img width="100%" :src="dialogImageUrlImg" alt="">
                        </el-dialog>
                        <span>
                        请上传小于200KB，比例1:1的图片
                        </span>
                    </el-form-item>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer2" >
                        <el-button @click="addClose">取 消</el-button>
                        <el-button type="primary" @click="addTodayHot('addForm')">确 定</el-button>
                        </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <!-- 新增弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="35%" >
            <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
                <el-row style="height: 350px">
                    <el-form-item label="文章标题" prop="title">
                        <el-input v-model="editForm.title" placeholder="文章标题"></el-input>
                    </el-form-item>
                    <el-form-item label="文章链接" placeholder="文章链接"  prop="url">
                        <el-input v-model="editForm.url"></el-input>
                    </el-form-item>

                    <el-form-item label="是否置顶" prop="isTop">
                        <el-radio-group v-model="editForm.isTop">
                            <el-radio label="0">否</el-radio>
                            <el-radio label="1">是</el-radio>
                        </el-radio-group>
                        默认不置顶，不置顶按创建时间倒序显示
                    </el-form-item>
                    <el-form-item label="上传缩列图" prop="img">
                        <el-upload
                                :action="uploadUrl"
                                list-type="picture-card"
                                :class="{disabled:uploadNum==1}"
                                :limit="limit"
                                :file-list="picList"
                                :on-preview="handlePictureCardPreviewImg"
                                :on-success="successUploadImg"
                                :before-upload="beforeUpload"
                                :on-remove="handleRemoveImg">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisibleImg" size="tiny">
                            <img width="100%" :src="dialogImageUrlImg" alt="">
                        </el-dialog>
                        <span>
                        请上传小于200KB，比例1:1的图片
                        </span>

                    </el-form-item>
                </el-row>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editClose()">取 消</el-button>
                <el-button type="primary" @click="editTodayHot('editForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {deleteTodayHot, getHotList, saveTodayHot, updateTodayHot} from '../../../../api/hot/hot'

export default {
    name: 'hotList',
    data() {
        return {
            query: {
                startTime:'',
                endTime:'',
                pageNo: 1,
                pageSize: 20
            },
            tableData: [],
            multipleSelection: [],
            picList:[],
            delList: [],
            editVisible: false,
            addVisible:false,
            uploadUrl:'https://lht.ah-zk.com/qjt/fs/file/upload',
            origin:'https://lht.ah-zk.com/qjt/fs/origin',
            uploadNum:0,
            dialogImageUrlImg: '',
            dialogVisibleImg: false,
            dialogImageUrlPro: '',
            dialogVisiblePro: false,
            limit:1,
            pageTotal: 0,
            form: {
                startTime:'',
                endTime:''
            } ,addForm:{
                title:'',
                url:'',
                isTop:'0',
                img:''
            },editForm: {
                id:'',
                title:'',
                url:'',
                isTop:'0',
                img:''
            },addRules: {
                title: [
                    { required: true, message: '请输入文章标题', trigger: ['blur','change'] }
                ],
                url:[
                    { required: true, message: '请输入文章链接', trigger: ['blur','change'] }
                ],
                img:[
                    { required: true, message: '请上传图片', trigger: ['blur','change'] }
                ]
            },editRules: {
                title: [
                    { required: true, message: '请输入文章标题', trigger: ['blur','change'] }
                ],
                url:[
                    { required: true, message: '请输入文章链接', trigger: ['blur','change'] }
                ],
                img:[
                    { required: true, message: '请上传图片', trigger: ['blur','change'] }
                ]
            },
            idx: -1,
            id: -1,
            data: [{
                label: '中国',
                children: [
                    {
                        label: '广东省',
                        children: [
                            {
                                label: '广州市'
                            },{
                                label: '深圳市'
                            }
                        ]
                    },
                    {
                        label: '江西省',
                        children: [
                            {
                                label: '九江市'
                            },{
                                label: '南昌市'
                            }
                        ]
                    }
                ]
            }],
            defaultProps: {
                children: 'children',
                label: 'label'
            }
        };
    },
    created() {
        this.getData();
    },
    props:['auths'],
    methods: {
        handleNodeClick(data) {
        },
        /**
         * 获取列表
         */
        getData() {
            getHotList(this.query).then(res => {
                console.log(res);
                this.tableData = res.data.records;
                this.pageTotal = res.data.total || 50;
            });
        },
        dateChange(val){
            console.log("time----->"+val)
            if(val!=null && val!==undefined && val.length>0){
                this.query.startTime = new Date(val[0]).getTime();
                this.query.endTime = new Date(new Date(val[1]).setHours(23,59,59)).getTime();
            }else{
                this.query.startTime = null;
                this.query.endTime = null;
            }
        },
        /**
         * 弹窗新增用户
         */
        addUser(){
            this.resetForm('addForm');
            this.picList = [];
            this.uploadNum=0;

            this.addVisible = true;
        },/**
         * 点击保存用户
         */
        addTodayHot(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // this.fullscreenLoading=true;
                    saveTodayHot(this.addForm).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.fullscreenLoading=false;
                            this.addVisible = false;
                            this.$message({
                                message: '新增成功',
                                type: 'success'
                            });
                            this.resetForm('addForm');
                            this.getData();
                            this.picList = [];
                        } else {
                            this.fullscreenLoading=false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageNo', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                let ids =[];
                ids.push(row.id);
                deleteTodayHot({id:row.id}).then(res => {
                    if (res.code == '0') {
                        this.$message.success('删除成功');
                        this.getData();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                });
            })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.editForm = row;
            this.editForm.isTop = ''+row.isTop+'';

            this.editVisible = true;
            this.picList = [];
            if(this.editForm.img){
                let json ={
                    name:'aa',
                    url:this.origin+"/"+this.editForm.img
                }
                this.picList.push(json);
                this.uploadNum=1;
            }
        },addClose(){
            this.addVisible = false;
            // this.picList = [];
        },editClose(){
            this.editVisible = false;
            this.picList = [];

        },
        // 保存编辑
        editTodayHot(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.fullscreenLoading=true;
                    updateTodayHot(this.editForm).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.fullscreenLoading=false;
                            this.editVisible = false;
                            this.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            this.resetForm('addForm');
                            this.getData();
                            this.picList = [];

                        } else {
                            this.fullscreenLoading=false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageNo', val);
            this.getData();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'pageSize', val);
            this.getData();
        },
    //图片上传删除图片
    handleRemoveImg(file, fileList) {
        this.uploadNum=0;
        this.addForm.img = null;
        this.editForm.img = null;
    },
    //图片放大方法
    handlePictureCardPreviewImg(file) {
        this.dialogImageUrlImg = file.url;
        this.dialogVisibleImg = true;
    },
    //图片上传成功回调
    successUploadImg(response,file,fileList){
        let f = response.files[0];
        this.addForm.img = f.fingerprint;
        this.editForm.img = f.fingerprint;

        this.uploadNum=1;
    },
    //文件上传时做文件大小判断
    beforeUpload(file){
        const isLt2M = file.size / 1024 / 1024 < 0.2
        if(!isLt2M) {
            this.$message({
                message: '上传文件大小不能超过 200KB!',
                type: 'warning'
            });
        }
        return isLt2M;
    },
    //初始化方法
    dataInit(){
        this.editForm = this.editData;
        if(this.editData.img){
            let json ={
                name:'aa',
                url:this.origin+"/"+this.editData.img
            }
            this.picList.push(json);
            this.uploadNum=1;
        }

        this.editIndex = this.index;
    },
    }
};
</script>

<style>
    .disabled .el-upload--picture-card {
        display: none;
    }
</style>
<style scoped>

.content-wrapper{
    height:100%;
    overflow-y: hidden;
}

.content-row{
    height: 100%;
}

.height-init{
    height: 100%;
}

.container{
    height: 100%;
}

.handle-box {
    height: 6.5%;
}

.handle-input {
    width: 120px;
    display: inline-block;
}

.list-table-row{
    height:83%;
}

.table {
    width: 100%;
    height: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.ml10 {
    margin-left: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.pagination-self{
    height:10%;
    text-align: right;
    margin-top: 5px;
}.dialog-footer2{
     margin: 10px 0px;
     height: 60px;
     padding-top: 600px;
     box-sizing: border-box;
     text-align: right;
    z-index: 1000000;
 }
</style>
